package com.goods.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.mapper.*;
import com.goods.business.service.IInStockService;
import com.goods.common.model.business.*;
import com.goods.common.utils.ListPageUtils;
import com.goods.common.vo.business.InStockDetailVO;
import com.goods.common.vo.business.InStockItemVO;
import com.goods.common.vo.business.InStockVO;
import com.goods.common.vo.business.SupplierVO;
import com.goods.common.vo.system.PageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA
 *
 * @Date: 2023/3/7 - 10:49
 * @Author: Hyoung
 * @Description:
 */
@Service
public class InStockServiceImpl implements IInStockService {

    @Autowired
    private IInStockMapper iInStockMapper;


    @Autowired
    private ISupplierMapper iSupplierMapper;

    @Autowired
    private IProductStockMapper iProductStockMapper;


    @Autowired
    private IInStockInfoMapper iInStockInfoMapper;

    @Autowired
    private IProductMapper iProductMapper;

    @Override
    public PageVO<InStockVO> findInStockList(Integer pageNum, Integer pageSize, InStockVO inStockVO) {
        PageHelper.startPage(pageNum, pageSize);
        String inNum = inStockVO.getInNum();
        Integer type = inStockVO.getType();
        Integer status = inStockVO.getStatus();
        Date startTime = inStockVO.getStartTime();
        Date endTime = inStockVO.getEndTime();
        Example inStockExample = new Example(InStock.class);
        Example.Criteria criteria = inStockExample.createCriteria();

        // 做条件
        if (!StringUtils.isEmpty(inNum)) {
            criteria.andLike("inNum", "%" + inNum + "%");
        }
        if (!Objects.isNull(type)) {
            criteria.andEqualTo("type", type);
        }
        if (!Objects.isNull(status)) {
            criteria.andEqualTo("status", status);
        }
        if (!Objects.isNull(startTime) && !Objects.isNull(endTime)) {
            criteria.andBetween("createTime", startTime, endTime);
        }
        List<InStock> inStockList = iInStockMapper.selectByExample(inStockExample);
        List<InStockVO> collect = inStockList.stream().map(inStock -> {
            InStockVO inStockVOTemp = new InStockVO();
            // 查询物资提供方
            BeanUtils.copyProperties(inStock, inStockVOTemp);

            Supplier supplier = iSupplierMapper.selectByPrimaryKey(inStock.getSupplierId());
            inStockVOTemp.setSupplierName(supplier.getName());
            inStockVOTemp.setPhone(supplier.getPhone());
            return inStockVOTemp;

        }).collect(Collectors.toList());
        PageInfo<InStock> inStockPageInfo = new PageInfo<>(inStockList);

        return new PageVO<>(inStockPageInfo.getTotal(), collect);
    }

    @Override
    public void delete(Integer id) {
        InStock inStock = iInStockMapper.selectByPrimaryKey(id);
        if (Objects.isNull(inStock)) {
            return;
        }
        iInStockMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void publish(Integer id) {
        InStock inStock = iInStockMapper.selectByPrimaryKey(id);
        if (Objects.isNull(inStock)) {
            return;
        }
        inStock.setStatus(0);
        iInStockMapper.updateByPrimaryKey(inStock);
    }

    @Override
    public void back(Integer id) {
        InStock inStock = iInStockMapper.selectByPrimaryKey(id);
        if (Objects.isNull(inStock)) {
            return;
        }
        inStock.setStatus(2);
        iInStockMapper.updateByPrimaryKey(inStock);
    }

    @Override
    public void remove(Integer id) {
        InStock inStock = iInStockMapper.selectByPrimaryKey(id);
        if (Objects.isNull(inStock)) {
            return;

        }
        inStock.setStatus(1);
        iInStockMapper.updateByPrimaryKey(inStock);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addIntoStock(InStockVO inStockVO) {
        // 如果supplierId为空就回新建一个 否则直接关联关系
        Long supplierId = inStockVO.getSupplierId();
        if (Objects.isNull(supplierId)) {

            Supplier supplier = new Supplier();
            supplier.setName(inStockVO.getName());
            supplier.setAddress(inStockVO.getAddress());
            supplier.setEmail(inStockVO.getEmail());
            supplier.setPhone(inStockVO.getPhone());
            supplier.setCreateTime(new Date());
            supplier.setModifiedTime(new Date());
            supplier.setSort(inStockVO.getSort());
            supplier.setContact(inStockVO.getContact());
            iSupplierMapper.insert(supplier);

            inStockVO.setSupplierId(supplier.getId());
        }
        // instockinfo表 pnum innum 关联
        // 生成一个入库inNUm
        String inNum = UUID.randomUUID().toString().replace("-", "");
        inStockVO.setInNum(inNum);
        inStockVO.setCreateTime(new Date());
        inStockVO.setModified(new Date());
        Integer productNumberSum = new Integer(0);
        List<Object> productList = inStockVO.getProducts();
        for (Object product : productList) {
            HashMap<String, Integer> temp = (HashMap<String, Integer>) product;
            Long id = Long.valueOf(temp.get("productId"));
            Integer productNumber = temp.get("productNumber");
            productNumberSum += productNumber;

            Product productSource = iProductMapper.selectByPrimaryKey(id);
            if (!Objects.isNull(productSource)) {
                // 入库信息
                InStockInfo inStockInfo = new InStockInfo();
                inStockInfo.setInNum(inStockVO.getInNum());
                inStockInfo.setPNum(productSource.getPNum());
                inStockInfo.setProductNumber(productNumber);
                inStockInfo.setCreateTime(new Date());
                inStockInfo.setModifiedTime(new Date());
                iInStockInfoMapper.insert(inStockInfo);

                // 增加product数量
                String pNum = productSource.getPNum();
                Example exampleProductStock = new Example(ProductStock.class);
                exampleProductStock.createCriteria().andEqualTo("pNum", pNum);
                ProductStock productStock = iProductStockMapper.selectOneByExample(exampleProductStock);
                if (!Objects.isNull(productStock)) {
                    Long stock = productStock.getStock();
                    productStock.setStock(stock + productNumber);
                    //  修改更新数据的时间
                    // TODO商品数量没有增加
                    productSource.setModifiedTime(new Date());
                    iProductMapper.updateByPrimaryKey(productSource);
                    iProductStockMapper.updateByPrimaryKey(productStock);
                }
            }

        }
        inStockVO.setStatus(2);
        inStockVO.setProductNumber(productNumberSum);
        InStock inStock = new InStock();
        BeanUtils.copyProperties(inStockVO, inStock);
        iInStockMapper.insert(inStock);
        //
    }

    @Override
    public InStockDetailVO detailInStock(Integer id, Integer pageNum) {
        InStockDetailVO inStockDetailVO = new InStockDetailVO();

        InStock inStock = iInStockMapper.selectByPrimaryKey(id);
        inStockDetailVO.setInNum(inStock.getInNum());
        inStockDetailVO.setStatus(inStock.getStatus());
        inStockDetailVO.setType(inStock.getType());
        inStockDetailVO.setOperator(inStock.getOperator());

        // 获取supplier
        Long supplierId = inStock.getSupplierId();
        Supplier supplier = iSupplierMapper.selectByPrimaryKey(supplierId);
        SupplierVO supplierVO = new SupplierVO();
        BeanUtils.copyProperties(supplier, supplierVO);
        inStockDetailVO.setSupplierVO(supplierVO);
        //  获取总数
        inStockDetailVO.setTotal(inStock.getProductNumber());
        // 获取product
        // 需要一个    private List<InStockItemVO> itemVOS = new ArrayList<>();
        Example exampleInStock = new Example(InStockInfo.class);
        exampleInStock.createCriteria().andEqualTo("inNum", inStock.getInNum());
        List<InStockInfo> inStockInfoList = iInStockInfoMapper.selectByExample(exampleInStock);
        List<InStockItemVO> inStockItemList = new ArrayList<>();
        for (InStockInfo inStockInfo : inStockInfoList) {
            Integer productNumber = inStockInfo.getProductNumber();
            // 获取product
            Example exampleProduct = new Example(Product.class);
            exampleProduct.createCriteria().andEqualTo("pNum", inStockInfo.getPNum());
            Product product = iProductMapper.selectOneByExample(exampleProduct);
            if (!Objects.isNull(product)) {
                // 把商品组装成InStockItem
                InStockItemVO inStockItemVO = new InStockItemVO();
                BeanUtils.copyProperties(product, inStockItemVO);

                // 设置数量
                inStockItemVO.setCount(productNumber);
                inStockItemList.add(inStockItemVO);
            }
        }
        inStockDetailVO.setItemVOS(ListPageUtils.page(inStockItemList, 4, pageNum));
        System.out.println(inStockItemList);
        // 获取stockInfo
        return inStockDetailVO;
    }
}
